﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MAPDavy.Entities;
using MAPDavy.BusinessLogic;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

using System.IO;
using MvcSiteMapProvider;

namespace MAPDavy.WebMVC3.Controllers
{
    public class AnioLectivoController : Controller
    {
        public AnioLectivoController()
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();
                container.BuildUp(this.GetType(), this);
            }
        }

        [Dependency]
        public IAnioLectivoBL AnioLectivoBL { get; set; }

        //
        // GET: /AnioLectivo/

        [Authorize(Roles = "admin")]
        public ActionResult Index()
        {
            var anios = AnioLectivoBL.GetAllFromAnioLectivo(); 

            return View(anios);
        }

        //
        // GET: /AnioLectivo/Details/5
        [Authorize(Roles = "admin")]
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /AnioLectivo/Create
        [Authorize(Roles = "admin")]
        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /AnioLectivo/Create

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Create(FormCollection collection)
        {
            AnioLectivo anio = null;
        
            try
            {
                anio = new AnioLectivo()
                {
                    Anio = collection["Anio"].ToString(),
                    Descripcion = collection["Descripcion"].ToString(),
                    InicioAcademico = DateTime.Parse(collection["InicioAcademico"].ToString()),
                    NroDiasClase = Int32.Parse(collection["NroDiasClase"].ToString()),
                    Color = collection["Color"].ToString()
                };

                var isCerrado = collection["Cerrado"].ToString();

                anio.Cerrado = isCerrado == "false" ? false : true;

                AnioLectivoBL.AddAnioLectivo(anio);

                var path = Path.Combine(Server.MapPath("~/files/"+anio.Anio));

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                if (Request.Cookies["workspace"] == null)
                {
                    Response.Cookies["workspace"].Value = anio.Anio;
                    Response.Cookies["workspace"].Expires = DateTime.Now.AddDays(1);
                }

                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                ViewData["message"] = ex.Message;

                return View(anio);
            }
        }
        
        //
        // GET: /AnioLectivo/Edit/5

        [MvcSiteMapNode(Title = "Modificar Año", ParentKey = "AnioLectivo", Order = 0)]
        [Authorize(Roles = "admin")]
        public ActionResult Edit(int id = 0)
        {
            if (id == 0)
            {
                return RedirectToAction("Index", "AnioLectivo");
            }
            var anio = AnioLectivoBL.GetAnioLectivoByAnio(id.ToString());

            if (anio == null)
            {
                return RedirectToAction("Index", "AnioLectivo");
            }
            return View(anio);
        }

        //
        // POST: /AnioLectivo/Edit/5

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Edit(int id, FormCollection collection)
        {
            var cookieC = Request.Cookies["cerrado"];
            var cookie = Request.Cookies["workspace"];

            if (cookieC == null || cookie== null )
            {
                return RedirectToAction("Index", "Home");
            }

            try
            {
                AnioLectivo anio = new AnioLectivo() 
                {
                    Anio = collection["Anio"].ToString(),
                    Descripcion = collection["Descripcion"].ToString(),
                    InicioAcademico = DateTime.Parse(collection["InicioAcademico"].ToString()),
                    NroDiasClase = Int32.Parse(collection["NroDiasClase"].ToString()),
                    Color = collection["Color"].ToString()
                };

                var isCerrado = collection["Cerrado"].ToString();

                anio.Cerrado = isCerrado == "false"?false:true;

                AnioLectivoBL.EditAnioLectivo(anio);

                var path = Path.Combine(Server.MapPath("~/files/" + anio.Anio));

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (cookie.Value.ToString() == anio.Anio)
                {
                    Response.Cookies["cerrado"].Value = anio.Cerrado.ToString().ToLower();
                    Response.Cookies["cerrado"].Path = "/";
                    Response.Cookies["cerrado"].Expires = DateTime.Now.AddDays(1);

                    Response.Cookies["workspace"].Value = anio.Anio;
                    Response.Cookies["workspace"].Path = "/";
                    Response.Cookies["workspace"].Expires = DateTime.Now.AddDays(1);
                }                
 
                return RedirectToAction("Index");
            }
            catch(Exception ex) 
            {
                return View(ex.Message);
            }
        }

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult CanDeleteServiceJson(int id)
        {
            var can = AnioLectivoBL.CanDelete(id.ToString());

            return Json(can, JsonRequestBehavior.AllowGet);
        }

        [Authorize]
        public ActionResult GetAnioServiceJson(int an)
        {
            var anio = AnioLectivoBL.GetAnioLectivoByAnio(an.ToString());

            var a = new { anio =anio.Anio,desc = anio.Descripcion,color = anio.Color,cerrado = anio.Cerrado };

            return Json(a, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /AnioLectivo/Delete/5
 
        //public ActionResult Delete(int id)
        //{
        //    try
        //    {
        //        AnioLectivoBL.DeleteAnioLectivo(id.ToString());   

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}

        //
        // POST: /AnioLectivo/Delete/5

        [HttpPost]
        [Authorize(Roles = "admin")]
        public ActionResult Delete(int id)
        {
            try
            {
                AnioLectivoBL.DeleteAnioLectivo(id.ToString());

                return Json(true, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
